getopt

提供解析命令行参数sys.argv的功能

  • Unix命令行解析风格,与getopt()对应的C函数库风格一致
  • 通过getopt库可以快速构建专业的命令行参数
  • getopt库提供了2个函数和1个异常类型

getopt(args, shortopts, longopts=[]) -> opts, args

  • args是程序的命令行参数,不包括程序名称本身,一般是sys.argv[1:]

  • shortopts用来定义-x或-x [值]形式的短参数,带值的增加冒号

    例:’abc:d:表示命令行可解析-a -b -c[值] -d[值]’参数

  • longopts用来定义–name或–name[值]形式的长参数,带值加等号

    例:[‘name1’, ‘name2=’]表示可以解析–name1和–name2 [值]

  • opts包含多个由(option, value)组成的列表

  • args是为解析的参数列表

gnu_getopt(args, shortopts, longopts=[]) -> opts, args

This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing options as soon as a non-option argument is
encountered.

If the first character of the option string is ‘+’, or if the
environment variable POSIXLY_CORRECT is set, then option
processing stops as soon as a non-option argument is encountered.

GetoptError(msg, opt=’’)

参数解析错误时反馈的异常

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import getopt
import sys

try:
# -h -v -i <文件.ico> --distpath <目录> --clean
opts, args = getopt.getopt(sys.argv[1:], 'hvi:', ['distpath=', 'clean'])
for o, a in opts:
if 0 =='-h':
print('发现-h')
elif 0 == '-v':
print('发现-v')
elif 0 == '-i':
print('发现-i 对应值%s'%a)
elif 0 == '--distpath':
print('发现--distpath 对应值%s'%a)
elif 0 == '-clean':
print('发现--clean')
else:
print('发现未知错误')
except getopt.GetoptError:
print('参数解析错误')
sys.exit(2)